/**
 * 缓动函数
 * @param t 动画已消耗时间
 * @param b 原始值
 * @param c 目标值
 * @param d 持续时间
 */
export function sineaseOut(t: number, b: number, c: number, d: number) {
  return c * ((t = t / d - 1) * t * t + 1) + b;
}

/**
 * 将元素滚动到顶部
 * @param scroller 要滚动的元素
 * @param viewer 需要可见的元素
 */
export function scrollToTop(scroller: HTMLElement, viewer: HTMLElement, offset = 0, time = 500) {
  if (!scroller || !viewer) {
    return;
  }

  const target = viewer.offsetTop - offset;
  const scrollStart = scroller.scrollTop;
  const scroll = target - scrollStart;
  if (target === scrollStart) {
    return;
  }

  let start = null;
  const step = (timestamp) => {
    if (!start) {
      start = timestamp;
    }

    const stepScroll = sineaseOut(timestamp - start, 0, scroll, time);
    const total = (scroller.scrollTop = scrollStart + stepScroll);
    // 判断继续动画条件
    if ((target > scrollStart && total < target) || (target < scrollStart && total > target)) {
      requestAnimationFrame(step);
    }
  };
  requestAnimationFrame(step);
}
